package com.atmilan.quartz.sync.pull.europe.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.atmilan.quartz.model.entity.europe.EuropeBrand;
import com.atmilan.quartz.model.entity.europe.EuropeBrandResult;
import com.atmilan.quartz.sync.pull.buyer.service.IBuyerBrandService;
import com.atmilan.quartz.sync.pull.europe.mapper.EuropeBrandMapper;
import com.atmilan.quartz.sync.pull.europe.service.IEuropeBrandService;
import com.atmilan.quartz.sync.pull.europe.service.IEuropeService;
import com.atmilan.quartz.utils.EuropeSendXmlUtil;
import com.atmilan.quartz.utils.EuropeUtil;
import com.atmilan.quartz.utils.STAXUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.digest.DigestUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author hupeng
 */
@Slf4j
@Service
@Transactional
public class EuropeServiceImpl implements IEuropeService {

    @Value("${buyer.appkey}")
    private String appKey;

    @Value("${buyer.appsecret}")
    private String appSecret;

    @Value("${europe.url}")
    private String url;

    @Value("${europe.username}")
    private String username;

    @Value("${europe.password}")
    private String password;


    public static final String BUYER_BRAND_OP = "filter";
    public static final String BUYER_BRAND_ACTION = "brand";


/*
    private final IEuropeProvider provider;
*/

    @Autowired
    IBuyerBrandService buyerBrandService;

    @Autowired
    private EuropeBrandMapper europeBrandMapper;

    @Autowired
    private IEuropeBrandService europeBrandService;

/*
    @Autowired
    public EuropeServiceImpl(IEuropeProvider provider) {
        this.provider = provider;
    }
*/


    @Override
    public EuropeBrandResult getBrand() throws IOException {
        String sendMsg = "<tem:DictBrand>" + "</tem:DictBrand>";
        String sendXML = EuropeSendXmlUtil.getSendMsg(sendMsg);
        String respXml = EuropeUtil.getEuropeXml(username, password, url, sendXML);
        //解析xml文档
        List<EuropeBrand> brandList = new ArrayList<>();
        EuropeBrandResult europeBrandResult = new EuropeBrandResult();
        try {
            List<Map<String, Object>> europMapList = STAXUtil.getEuropMapList(respXml, "DictBrand");
            for(Map<String,Object> map : europMapList){
                EuropeBrand europeBrand = new EuropeBrand();
                europeBrand.setBrandId(Integer.parseInt((String)map.get("ID")));

                String brandName = (String) map.get("Name");
                europeBrand.setBrandName(brandName);
                String fristHead = brandName.substring(0, 1);
                if(fristHead.matches("[a-zA-Z]")){//首字母不为其他字符
                    europeBrand.setBrandZm(fristHead.toUpperCase());
                }else{
                    europeBrand.setBrandZm("#");
                }
                //判断此品牌在小黑仓中是否已存在
                QueryWrapper<EuropeBrand> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(EuropeBrand::getBrandName,europeBrand.getBrandName());
                EuropeBrand europeBrand1Brand = europeBrandService.getOne(queryWrapper);
                if(europeBrand1Brand == null){
                    europeBrand.setIsNew(1);//新品牌
                }else{
                    europeBrand.setIsNew(0);//此品牌在小黑仓中存在
                }
                europeBrand.setBrandSeries((String) map.get("Series"));
                europeBrand.setCreateTime(DateUtil.date());
                brandList.add(europeBrand);
                //europeBrandService.saveOrUpdate(europeBrand);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        europeBrandResult.setBrandList(brandList);
        return europeBrandResult;
    }

    @Override
    public String getBrandString() {
        return null;
    }

  /*  @Override
    public String getBrandString() {
        String timestamp = String.valueOf(Instant.now().getEpochSecond());
        String random = String.valueOf(ThreadLocalRandom.current().nextInt(1000, 9999));
        String signature = this.getSignature(timestamp, random);
        return this.provider.getBrandString(BUYER_BRAND_OP, BUYER_BRAND_ACTION, random, timestamp, appKey, appSecret, signature);
    }
*/

    private String getSignature(String timestamp, String random) {
        Map<String, String> signMap = MapUtil.newHashMap(4);
        signMap.put("timeStamp", timestamp);
        signMap.put("randomStr", random);
        signMap.put("appkey", this.appKey);
        signMap.put("appsecret", this.appSecret);

        List<String> valueList = signMap.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());

        String signStr = StringUtils.join(valueList, null);
        signStr = DigestUtil.sha1Hex(signStr);
        signStr = DigestUtil.md5Hex(signStr);
        signStr = DigestUtil.md5Hex(signStr);

        return signStr.toUpperCase();
    }
}
